package com.gt.quality.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gt.quality.config.SpringBeanUtil;
import com.gt.quality.system.entity.SysDept;
import com.gt.quality.base.pojo.LayGradleSelector;
import com.gt.quality.base.pojo.LayerTreeSelect;
import com.gt.quality.system.entity.vo.MenuTreeVo;
import com.gt.quality.system.mapper.SysDeptMapper;
import com.gt.quality.base.pojo.BaseLimitRequest;
import com.gt.quality.base.pojo.LayerListViewObject;
import com.gt.quality.system.service.SysDeptService;
import com.gt.quality.utils.CreateTreeUtils;
import jakarta.annotation.Resource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.ArrayList;
import java.util.List;


/**
 * 部门表(SysDept)表服务实现类
 *
 * @author makejava
 * @since 2026-11-25 16:30:08
 */
@Service("sysDeptService")
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Resource
    private SysDeptMapper sysDeptMapper;


    /**
     * Description:  分页查询
     *
     * @param limitRequest 分页查询参数
     * @author: makeJava
     * @date: 2026-02-02 14:57:06
     * @return:com.baomidou.mybatisplus.core.metadata.IPage
     */
    @Override
    public IPage<SysDept> queryLimitPage(BaseLimitRequest<SysDept> limitRequest) {
        SysDept requestBody = limitRequest.getRequestBody();
        IPage<SysDept> page = getByPageParam(limitRequest);
        JSONObject thisObj = JSONObject.from(requestBody);
        QueryWrapper<SysDept> queryWrapper = queryWrapperBuilder(thisObj, limitRequest);
        return sysDeptMapper.selectPage(page, queryWrapper);
    }

    /**
     * Description:  批量新增优化版
     *
     * @param entityList entityList
     * @author: makeJava
     * @date: 2026-02-02 19:54:59
     */
    @Override
    public Integer saveBatchByEasyBaseMapper(List<SysDept> entityList) {

        return sysDeptMapper.insertBatchSomeColumn(entityList);
    }

    @Override
    public LayerListViewObject buildTreeDeptInfo(List<SysDept> list, Long userId) {
        LayerListViewObject viewObject = new LayerListViewObject();
        List<LayGradleSelector> treeVoList = new ArrayList<>(list.size());
        for (SysDept item : list) {
            LayGradleSelector treeVo = CreateTreeUtils.buildSelectTreeVo(item.getDeptId(), item.getParentId(), item.getDeptName());
            treeVoList.add(treeVo);
        }
        List<LayGradleSelector> allMenu = CreateTreeUtils.createSelectTree(treeVoList);
        viewObject.setNextLayer(allMenu);
        if (userId != null) {
            SysDept thisMenu = sysDeptMapper.selectByUserId(userId);
            StringBuilder thisValue = new StringBuilder();
            if (thisMenu != null) {
                String[] split = thisMenu.getAncestors().split(",");
                for (int i = 1; i < split.length; i++) {
                    thisValue.append(split[i]).append("/");
                }
                thisValue.append(thisMenu.getDeptId());
            }
            viewObject.setCurrentLayer(thisValue.toString());
        }
        return viewObject;
    }

    @Override
    public LayerListViewObject buildTree() {
        LayerListViewObject viewObject = new LayerListViewObject();
        List<SysDept> list = sysDeptMapper.selectList(new QueryWrapper<>());
        List<MenuTreeVo> menuTreeVoList = new ArrayList<>(list.size());
        for (SysDept item : list) {
            MenuTreeVo menuTreeVo = CreateTreeUtils.buildMenuTreeVo(item.getDeptId(), item.getParentId(), item.getDeptName(), "layui-icon-template");
            menuTreeVoList.add(menuTreeVo);
        }
        List<MenuTreeVo> allMenu = CreateTreeUtils.createAnyThingTree(menuTreeVoList);
        // 默认首节点选中
        if (CollUtil.isNotEmpty(allMenu)) {
            allMenu.get(0).setChecked(true);
        }
        viewObject.setNextLayer(allMenu);
        viewObject.setCurrentLayer(null);
        return viewObject;
    }

    @Override
    public List<Long> selectDeptIdsByRoleId(Long roleId) {
        return sysDeptMapper.selectDeptIdsByRoleId(roleId);
    }

    @Override
    public List<LayerTreeSelect> queryToTree(List<SysDept> list, Long deptId) {
        // list找出改节点的所有父级节点--
        // 将祖先部门ID转换为Set以便快速查找
        java.util.Set<Long> ancestorIdSet = new java.util.HashSet<>();
        if (deptId != null) {
            // 查找指定部门的所有父级部门
            SysDept targetDept = list.stream().filter(dept -> dept.getDeptId().equals(deptId)).findFirst().orElse(null);
            if (targetDept != null) {
                // 获取所有祖先部门ID
                String[] ancestorIds = targetDept.getAncestors().split(",");
                for (String ancestorId : ancestorIds) {
                    if (!ancestorId.isEmpty()) {
                        try {
                            ancestorIdSet.add(Long.parseLong(ancestorId));
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
                // 添加目标部门本身
                ancestorIdSet.add(deptId);
            }
        }
        boolean hasDeptNeedOpen = !ancestorIdSet.isEmpty();
        // 封装成后续的返回值
        List<LayerTreeSelect> treeVoList = new ArrayList<>(list.size());
        for (SysDept item : list) {
            LayerTreeSelect treeVo = CreateTreeUtils.buildLayerTreeSelect(item.getDeptId(), item.getParentId(), item.getDeptName());
            // 过滤list，只保留目标部门及其祖先部门
            if (hasDeptNeedOpen && ancestorIdSet.contains(item.getDeptId())) {
                treeVo.setSpread(Boolean.TRUE);
            }
            treeVoList.add(treeVo);
        }
        return CreateTreeUtils.createLayerTreeSelect(treeVoList);
    }

    /**
     * 往上传递 SqlSessionFactory
     *
     * @return SqlSessionFactory
     */
    @Override
    public SqlSessionFactory getSqlSessionFactory() {
        return super.getSqlSessionFactory();
    }

    /**
     * 往上传递 Mapper
     *
     * @return Mapper
     */
    @Override
    public Class<?> getThisMapperClass() {
        return SysDeptMapper.class;
    }

    /**
     * 往上传递 Transaction
     *
     * @return Transaction
     */
    @Override
    public TransactionTemplate getSpringTx() {
        return SpringBeanUtil.getBean(TransactionTemplate.class);
    }
}


